package agriculture.service.imp;

import agriculture.bean.Payment;
import agriculture.config.AlipayTemplate;
import agriculture.exception.BusinessException;
import agriculture.mapper.PaymentMapper;
import agriculture.service.PaymentService;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@RequiredArgsConstructor
public class PaymentServiceImp extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    private final AlipayTemplate alipayTemplate;

    @Override
    public String createAlipayPayment(Payment payment) throws AlipayApiException {

        try {
            payment.setPayType(payment.getPayType());
            payment.setOrderNumber(payment.getOrderNumber());
            payment.setPayAmount(payment.getPayAmount());
            payment.setPayStatus("UNPAID");
            payment.setCreateTime(LocalDateTime.now());
            payment.setQuantity(payment.getQuantity());

            this.save(payment); // 插入数据库
            return alipayTemplate.pay(payment);
        }catch (DuplicateKeyException e) {
            //立即查询最新状态（可能其他线程已支付成功）
           Payment latest = this.lambdaQuery()
                    .eq(Payment::getOrderNumber, payment.getOrderNumber()).one();
           if (latest != null && "PAID".equals(latest.getPayStatus())) {
               throw new BusinessException("订单已完成支付，请误重复支付");
           }else {
               throw new BusinessException("订单正在处理中，请稍后查看支付状态");
           }
        }
    }

}


